package com.basemanage.controller.sys;

import java.util.HashSet;
import java.util.Set;

import com.basemanage.core.controller.JCBaseController;
import com.basemanage.core.model.Condition;
import com.basemanage.core.model.Operators;
import com.basemanage.core.util.CommonUtils;
import com.basemanage.core.util.JqGridModelUtils;
import com.basemanage.core.view.InvokeResult;
import com.basemanage.model.SysRole;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 *角色控制器 
 */
public class RoleController extends JCBaseController {
	

	/**
	 * 跳转列表页面
	 */
	public void index() {
		render("role_index.html");
	}
	
	/**
	 * 跳转添加页面
	 */
	public void add() {
		Integer id=this.getParaToInt("id");
		if(id!=null){
			this.setAttr("item", SysRole.dao.findById(id));
		}
		this.setAttr("id", id);
		render("role_add.html");
	}
	
	/**
	 * 获取列表数据
	 */
	public void getListData() {
		String name=this.getPara("name");
		Set<Condition> conditions=new HashSet<Condition>();
		if(CommonUtils.isNotEmpty(name)){
			conditions.add(new Condition("name",Operators.LIKE,name));
		}
		Page<SysRole> pageInfo=SysRole.dao.getPage(this.getPage(), this.getRows(),conditions,this.getOrderby());
		
		this.renderJson(JqGridModelUtils.toJqGridView(pageInfo)); 
	}

	/**
	 * 启用/禁用
	 */
	public void setVisible(){
		Integer visible=this.getParaToInt("visible");
		String bids=this.getPara("ids");
		int flag=SysRole.dao.setVisible(bids, visible);
		InvokeResult result=new InvokeResult();
		if(flag==-1){
			result=InvokeResult.failure("超级管理员不能被修改");
		}else{
			result=InvokeResult.success();
		}
		this.renderJson(result);
	}

	/**
	 * 获取角色树
	 */
	public void getZtree(){
		Integer type=this.getParaToInt("type");
		Integer roleId=this.getParaToInt("roleId");
		String result=SysRole.dao.getZtreeViewList(type, roleId);
		this.setAttr("jsonTree", InvokeResult.success(result));
		this.setAttr("roleId", roleId);
		render("menu_assign.html");
	}
	
	/**
	 * 角色绑定资源.
	 */
	@Before(Tx.class)
	public void saveMenuAssign(){
		Integer roleId=this.getParaToInt("roleId");
		String menuIds=this.getPara("menuIds");
		InvokeResult result=new InvokeResult();
		if(roleId.equals(1)){
			result= InvokeResult.failure("超级管理员不能被修改");
		}else{
			SysRole.dao.saveMenuAssign(menuIds, roleId);
			 result=InvokeResult.success();
		}
		this.renderJson(result);
	}
	
	public void save(){
	    SysRole.dao.save(this.getParaToInt("id"),this.getPara("name"),this.getPara("des"));
		this.renderJson(InvokeResult.success());
	}
	
}





